// pages/login/login.js
import routeAPI from '../../config/route.js'; // 引入配置文件

Page({
  data: {
    applicationConfig: {
      applicationName: 'WJ学习资料小程序',
      applicationLogo: '/static/crms-uni-app-logo.png',
      applicationDesc: '欢迎使用WJ学习资料小程序'
    },
    errorMessage: '',
    privacyCheckboxChecked:false,
    customerAgreementUrl: 'https://example.com/customer-agreement',
    customerAgreementText: '用户协议',
    privacyPolicyUrl: 'https://example.com/privacy-policy',
    privacyPolicyText: '隐私政策',
    agreePrivacy: false,
    showPhoneNumberModal: false // 控制 modal 的显示
  },
  checkPrivecy(){
    if(this.privacyCheckboxChecked)
      return true;
    else{
      wx.showToast({
        icon: 'none',
        title:'请先同意隐私政策和用户协议'
      });
      return false;
    }
  },
  changeCheckbox(e) {
    const value = e.detail.value;
    this.setData({
        agreePrivacy: value.includes('privacy'),
    });
    this.privacyCheckboxChecked=value.includes('privacy')

  },
  navWebView(event) {
    const url = event.currentTarget.dataset.url;
    wx.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(url)}`
    });
  },
  getPhoneNumber(e) {
    let code = e.detail.code;
    //用户同意获取手机号码
    if(code){
      this.createUser(code);
    }
    this.setData({
        showPhoneNumberModal: false // 隐藏 modal
    });
  },
loginRedirect(){
  var that = this;
  if(that.to){
    wx.navigateTo({
      url: that.to
    })
  }else{
    uni.switchTab({
      url: '/pages/login/login'
    })
  }
},
closePopup(refName){
				this.$refs[refName].close();
},
setPhoneNumber() {
    console.log('使用其他电话号码');
    // 处理使用其他电话号码的逻辑
    this.setData({
        showPhoneNumberModal: false // 隐藏 modal
    });
  },
  successLogin(user_id){
    wx.setStorageSync('userId', user_id);
    wx.switchTab({
      url: '/pages/home/home'
    });
  },
  getUserInfo(openid, session_key,userAPI,code) {
    const that = this;
    wx.getUserInfo({
      success: function(infoRes) {
          const encryptedData = infoRes.encryptedData;
          const iv = infoRes.iv;

          // 发送 encryptedData 和 iv 到服务器
          wx.request({
              url: userAPI,
              method: 'POST',
              data: {
                  openid: openid,
                  session_key: session_key,
                  encryptedData: encryptedData,
                  iv: iv,
                  code: code
              },
              header: {
                Authorization: `Bearer ${wx.getStorageSync('token')}`
             },
            success: function(userRes) {
                  if(userRes.statusCode===200){
                     that.successLogin(userRes.data.user_id);
                  }else{
                    console.error('获取用户信息失败,请重新登陆');              
                  }
              },
              fail: function(err) {
                console.error('获取用户信息失败:', response.data.message);              
              }
          });
      },
      fail: function(err) {
          console.error('Get user info failed:', err);
      }
    });
  },
  wechatLogin() {
    if(!this.checkPrivecy()){
      return;
    }
    this.wechatUserLogin(routeAPI.default.api.login,null);
  },
  createUser(code) {
    if (code) {
      wx.login({
        success:async (res) => {
          if(res.code){
            const response =  await new Promise((resolve, reject) => {
              wx.request({
                url: routeAPI.default.api.userToken, // 替换为实际后端接口地址
                method: 'GET',
                data: {
                  code: code
                },
                success: resolve,
                fail: reject
              });
            });
            if (response.statusCode === 200) {
              const { access_token } = response.data;
              wx.setStorageSync('token', access_token);
              const { openid, session_key } = this.data;
              this.getUserInfo(openid, session_key,routeAPI.default.api.create,code);
            } else {
              console.error('获取用户信息失败:', response.data.message);
            }
          }
          
        }
      })
     
    }
  },
  wechatUserLogin(address) {
    const that = this;
    wx.login({
      success: async (res) => {
        if (res.code) {
          try {
            // 发送 code 到后端进行登录处理
            const response = await new Promise((resolve, reject) => {
              wx.request({
                url: address, // 替换为实际后端接口地址
                method: 'POST',
                data: {
                  code: res.code
                },
                success: resolve,
                fail: reject
              });
            });

            const data = response.data;
            if (response.statusCode === 200) {
              const { openid, session_key,user_id } = data;
              this.setData({
                openid: openid,
                session_key: session_key,
                user_id: user_id
              });
              // 假设后端返回用户信息，这里简单模拟存储用户 ID 和跳转
               // 获取用户信息
               if(user_id===null||user_id===''||user_id===undefined){
                this.setData({
                  showPhoneNumberModal: true // 显示 modal
                });
               }else{
                that.successLogin(user_id);
               }
            } else {
              this.setData({
                errorMessage: '登录失败，请稍后再试'
              });
            }
          } catch (error) {
            console.error('登录请求失败:', error);
            this.setData({
              errorMessage: '登录请求失败，请稍后再试'
            });
          }
        } else {
          this.setData({
            errorMessage: '登录失败，无法获取登录凭证'
          });
        }
      },
      fail: () => {
        this.setData({
          errorMessage: '登录失败，调用登录接口出错'
        });
      }
    });
  },
  
});